<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容显示区域 -->
    <el-card>
      <!-- 搜索框和添加用户按钮区域 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="usersInfo.query"
            clearable
            @clear="getUsersInfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersInfo"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表信息展示区域 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scoped">
            <el-switch
              v-model="scoped.row.mg_state"
              @change="userStateChange(scoped.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 用户信息修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <!-- 用户信息删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 用户角色权限分配按钮 -->
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--  分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="usersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户时弹出的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addFormClosed"
    >
      <!-- 对话框正文内容 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="70px"
        :rules="addFormRule"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 对话框底部取消确认按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息时弹出的对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="editFormClosed"
    >
      <!-- 修改用户信息表单 -->
      <el-form
        ref="editFormRef"
        :rules="editFormRule"
        :model="editForm"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>用户名：{{ dialogUserInfo.username }}</p>
        <p>当前角色：{{ dialogUserInfo.role_name }}</p>
        选择角色：<el-select v-model="selectedRole" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUsersInfo()
  },
  data() {
    /* 验证邮箱的验证规则 */
    var checkEmail = (rule, value, cb) => {
      /* 验证邮箱的正则表达式 */
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('输入的邮箱不合法！'))
    }
    /* 验证手机号的验证规则 */
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('输入的手机号不合法！'))
    }

    return {
      usersInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editDialogVisible: false,
      /* 修改表单数据 */
      editForm: {},
      /* 添加用户表单验证规则 */
      addFormRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      /* 修改用户信息表单验证规则 */
      editFormRule: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      /* 控制分配角色对话框的显示与隐藏 */
      setRoleDialogVisible: false,
      /* 分配角色对话框用户信息 */
      dialogUserInfo: {},
      /* 保存所有角色 */
      roleList: [],
      /* 下拉框选择的角色 */
      selectedRole: ''
    }
  },
  methods: {
    /* 获取用户信息 */
    async getUsersInfo() {
      const { data: res } = await this.$http.get('users', {
        params: this.usersInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    /* 修改每页信息显示条数 */
    handleSizeChange(newSize) {
      this.usersInfo.pagesize = newSize
      this.getUsersInfo()
    },
    /* 修改当前显示页数 */
    handleCurrentChange(newPage) {
      this.usersInfo.pagenum = newPage
      this.getUsersInfo()
    },
    /* 通过switch改变用户的状态并在数据库进行保存 */
    async userStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('用户状态改变失败！')
        userInfo.mg_state = !userInfo.mg_state
        return
      }
      this.$message.success('用户状态改变成功！')
    },
    /* 确认添加用户按钮 */
    async addUser() {
      const { data: res } = await this.$http.post('users', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error('添加用户失败！')
      }

      /* 添加用户成功 */
      this.$message.success('添加用户成功！')
      /* 关闭添加用户对话框 */
      this.addDialogVisible = false
      /* 更新用户列表 */
      this.getUsersInfo()
    },
    /* 监听添加用户对话框关闭 */
    addFormClosed() {
      this.$refs.addFormRef.resetFields()
    },
    /* 监听修改用户信息按钮 */
    async editUser(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    /* 监听修改用户信息对话框关闭-重置表单信息 */
    editFormClosed() {
      this.$refs.editFormRef.resetFields()
    },
    /* 确认修改用户信息按钮 */
    editUserInfo() {
      this.$refs.editFormRef.validate(async (value) => {
        if (!value) {
          return this.$message.error('信息填写不合法！')
        }

        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('用户信息修改失败！')
        }
        this.$message.success('用户信息修改成功！')
        this.editDialogVisible = false
        this.getUsersInfo()
      })
    },
    /* 删除用户信息 */
    removeUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败！')
          }
          this.$message.success('删除用户成功！')
          this.getUsersInfo()
        })
        .catch(() => {
          this.$message.info('取消删除用户！')
        })
    },
    /* 为用户分配角色对话框 */
    async showSetRoleDialog(role) {
      /* 获取所有角色 */
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色信息获取失败！')
      }
      this.roleList = res.data
      this.dialogUserInfo = role
      this.setRoleDialogVisible = true
    },
    /* 分配角色 */
    async setRole() {
      const {data:res} = await this.$http.put(`users/${this.dialogUserInfo.id}/role`, {rid:this.selectedRole})
      if(res.meta.status !== 200){
        return this.$message.error('分配角色失败！')
      }
      this.$message.success('分配角色成功！')
      this.setRoleDialogVisible = false
      this.getUsersInfo()
    },
    /* 监听分配角色对话框的关闭 */
    setRoleDialogClosed() {
      this.dialogUserInfo = {}
      this.selectedRole = ''
    }
  },
}
</script>

<style lang="less" scoped>
</style>